package com.aliang.shopping.task;

import cn.hutool.json.JSONUtil;
import com.aliang.shopping.contact.BasicConstant;
import com.aliang.shopping.util.SearchHostUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Executor;

/**
 * 热门搜索删除定时任务
 */
@Slf4j
@Component
@EnableAsync
@EnableScheduling
public class HostSearchDelTask {
    @Bean(name = "TaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(7);
        executor.setMaxPoolSize(42);
        executor.setQueueCapacity(11);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    }
    @Resource
    private SearchHostUtil searchHostUtil;

    //每天凌晨执行
    @Async("TaskExecutor")
    @Scheduled(cron = "59 59 23 * * ? ")
    public void testSchedule() {
        try {
            //热门搜索前10后的数据定时移除
            searchHostUtil.remove(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //每天凌晨执行
    @Async("TaskExecutor")
    @Scheduled(cron = "59 59 23 * * ? ")
    public void removePhoneIpCount() {
        try {
            // 手机验证码发送次数定时移除
            Set<String> keys = redisTemplate.keys(BasicConstant.SHOPPING_SEND_PHONE_KEY + "*");
            System.out.println(JSONUtil.toJsonStr(keys));
            if (Objects.nonNull(keys))
                redisTemplate.delete(keys);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}